package cn.jbolt.ai.core.chain.node.action.klb;

import cn.hutool.core.util.StrUtil;
import cn.jbolt.ai.core.chain.node.base.AppConfigConstant;
import cn.jbolt.ai.core.chain.ChainContext;
import cn.jbolt.ai.core.chain.node.provider.CaseNodeProvider;
import cn.jbolt.ai.klb.entity.AiDoc;
import cn.jbolt.ai.klb.entity.AiKnowledgeBase;
import cn.jbolt.ai.klb.service.AiKnowledgeBaseService;
import cn.jbolt.util.Result;
import com.fasterxml.jackson.databind.JsonNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 用于构建知识库查询节点
 */
@Component
public class KlbSearchNodeProvider implements CaseNodeProvider {
    private static final Logger logger = LoggerFactory.getLogger(KlbSearchNodeProvider.class);
    @Autowired
    private AiKnowledgeBaseService aiKnowledgeBaseService;

    @Override
    public String provide(JsonNode nodeConfig, ChainContext context) {
        KlbSearchNodeConfig config = KlbSearchNodeConfig.from(nodeConfig.get(AppConfigConstant.CONFIG_TYPE_KLB_SEARCH));
        if (nodeConfig.has(AppConfigConstant.CONFIG_TYPE_KLB_SEARCH) == false) {
            logger.error("APP [{}:{}] 未检测到知识库配置", context.getAiApp().getSn() ,context.getAiApp().getName());
            if (config.isOutputToResponse()){
                context.sendErrorMsg("未检测到知识库配置");
            }
            throw new RuntimeException("未检测到知识库配置");
        }

        if (config.getKlbId() == null || config.getKlbId() <= 0) {
            logger.error("APP [{}:{}] 未绑定知识库", context.getAiApp().getSn() ,context.getAiApp().getName());
            if (config.isOutputToResponse()){
                context.sendErrorMsg("未绑定知识库");
            }
//            throw new RuntimeException("未绑定知识库");
            return AppConfigConstant.AFTER_KEY_KLB_NOMATCH;
        }


        AiKnowledgeBase klb = aiKnowledgeBaseService.getById(config.getKlbId());
        if (klb == null || klb.getEnable() == false) {
            logger.error("APP [{}:{}] 知识库[{}]未启用", context.getAiApp().getSn() ,context.getAiApp().getName(), klb.getName());
            if (config.isOutputToResponse()){
                context.sendErrorMsg("知识库不可用");
            }
            throw new RuntimeException("知识库不可用");
        }

        Result<List<AiDoc>> result = aiKnowledgeBaseService.getDocListByKnowledgeBaseId(klb.getId(), context.getAttr(config.getInputField()),
                config.getLimit(), config.getMinScore());

        if (result.isError() && result.getCode() != Result.ERROR_VDB_NOMATCH ) {
            logger.error("知识库检索时发生异常：{}",  result.getMsg() );
            throw new RuntimeException("知识库检索时发生异常："+result.getMsg());
        }
        List<AiDoc> list = result.getData();

        if (list == null || list.isEmpty()) {
            return AppConfigConstant.AFTER_KEY_KLB_NOMATCH;
        }


        //将结果保存到 输出字段中
        if (list != null && list.isEmpty() == false && StrUtil.isNotBlank(config.getOutputField())) {

            context.setAttr(config.getOutputField(), list);
        }

        return AppConfigConstant.AFTER_KEY_KLB_MATCH;
    }
}
